*** Run Synthetic controls on fit lead/lags

cd /disk/agedisk3/medicare.work/poterba-DUA52260/jetson-dua52260/outliers/synth/100pct/robustness/feout
use types_panel_feout.dta, clear

tsset group dt 

*** Merge leads and lags
merge m:1 group using groupleadlags.dta
drop _merge mindistance


** Store group levels in macro
levelsof group, local(levels)


*** Replace generate with fitted lead/lags
sort group dt
gen out = .


foreach g of local levels{
	disp `g'
	* Treated group gets no time shift
	if `g' == 999{
		replace out = pmt_amt if group == `g'
		continue
		}

	** Grab the stored shifter 
	qui summarize period if group == `g'
	local shift = r(min)

	** If positive, create lead 
	if `shift' > 0{
		replace out = F`shift'.pmt_amt if group == `g'
	}
	** If negative, create lag 
	if `shift' < 0{
		local shiftvalue = abs(`shift')
		replace out = L`shiftvalue'.pmt_amt if group == `g'
	}

	if `shift' == 0{
		replace out = pmt_amt if group == `g'
	}
}




*** We're using filing of the Tenet Lawsuit
*** 11/4/2002
disp mofd(mdy(11, 4, 2002))
	* 514

** Cut missing data from front of time series
** Which is limited by the highest lag 
summarize period
drop if dt < mofd(mdy(1,1,1999)) + abs(r(min))

*** Cut missing data from end of time series
*** Which is limited by furthest lead
*** Data end end of 2016
summarize period
drop if dt > mofd(mdy(12, 31, 2016)) - abs(r(max))

log using synth.log, replace 
synth out out, trunit(999) trperiod(514) figure
log close 
************************************
************************************
*** Store fitted values
matrix fit = e(Y_synthetic)
keep if group == 999
svmat fit 
save synth_fit.dta, replace 


